package org.zyj.controller;

import com.alibaba.fastjson.JSONObject;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.zyj.dto.MessageDto;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@RestController
public class TestController {
    @Resource
    private RabbitTemplate rabbitTemplate;
    @Resource
    private RedisTemplate redisTemplate;
    /**
     * 充当生产者发消息的测试接口
     */
    @GetMapping("/test")
    public String test() {
        for (int i = 1; i <= 10; i++) {
            int count = i;
            new Thread(() -> {
                try {
                    MessageDto dto = new MessageDto();
                    dto.setId(incr("incrId", -1));
                    dto.setCreateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                    dto.setMessage("hello,RabbitMQ,count=" + count);
//发送消息
                    rabbitTemplate.convertAndSend("TestExchange01",
                            "TestRouting", JSONObject.toJSONString(dto));
                    System.out.println("发送消息=" + dto);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }).start();
        }
        return "操作成功";
    }
    /**
     * 获取递增值
     */
    public Integer incr(String key, long liveTime) {
        RedisAtomicLong entityIdCounter = new RedisAtomicLong(key,
                Objects.requireNonNull(redisTemplate.getConnectionFactory()));
        Long increment = entityIdCounter.incrementAndGet();//获取递增值，从1开始
        //如果设置了过期时间，就设置超时时间（单位：秒）
        if (increment == 0 && liveTime > 0) {
            entityIdCounter.expire(liveTime, TimeUnit.SECONDS);
        }
        return Integer.valueOf(String.valueOf(increment));
    }
}
